package com.toman.ui.work.workshop;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshScrollView;
import com.king.zxing.CaptureActivity;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.request.GetRequest;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.InspectionReportDto;
import com.toman.R;
import com.toman.Util.ActionCallback;
import com.toman.Util.BaseNetUtil;
import com.toman.Util.DialogUtils;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.DialogBean;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.ClearEditText;
import com.toman.widget.callback.StringLoadingCallback;

import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

import static com.toman.Interfaces.NewBaseUrl.SCANNING_CODE;


//巡检报工
public class InspectionReportActivity extends ToolBarActivity {
    @BindView(R.id.et_search)
    ClearEditText etSearch;
    @BindView(R.id.tv_select)
    TextView tvSelect;
    @BindView(R.id.fl_et)
    RelativeLayout flEt;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.mPullToRefreshScrollView)
    PullToRefreshScrollView mPullToRefreshScrollView;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    private InspectionReportDto bean;
    CommonAdapter<InspectionReportDto> adapter;
    private List<InspectionReportDto> list = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inspection_report);
        ButterKnife.bind(this);
        initToolBar(BaseEnum.INSPECTIONREPORT.name);

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (!StringUtils.isEmpty(getIntent().getStringExtra("status"))) {
//            setSelect(getIntent().getStringExtra("status"));
//        } else {
//            customer(1, 1, etSearch.getText().toString());
//        }
        customer(1, 1, etSearch.getText().toString());

    }

    private void initView() {
        initAdapter();
        etSearch.setHint("产线名称/品名");

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<InspectionReportDto> beanlist = adapter.getDatas();
                InspectionReportDto bean = beanlist.get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", bean);
                bundle.putString("status", bean.getAuditStatus());
                IntentUtils.startActivity(InspectionReportActivity.this, InspectionReporInfActivity.class, bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        lv.setAdapter(adapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
        };
        lv.setLayoutManager(linearLayoutManager);
        mPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                dialog = null;
                dialogList.clear();
                page = 2;
                customer(1, 1, etSearch.getText().toString().trim());
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                customer(page, 2, etSearch.getText().toString().trim());
                page += 1;


            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                customer(1, 1, s.toString().trim());

            }
        });
    }

    private void initAdapter() {
        adapter = new CommonAdapter<InspectionReportDto>(this, R.layout.reuse_list_workshop, list) {
            @Override
            protected void convert(ViewHolder holder, InspectionReportDto item, final int position) {
                holder.setText(R.id.tv_time, item.getCreateTime());
//                holder.setText(R.id.tv_code, item.getSendworkorderEntity().getSendworkCode());
                holder.getView(R.id.tv_code).setVisibility(View.GONE);
                holder.getView(R.id.iv_status).setVisibility(View.GONE);
                holder.getView(R.id.cb_status).setVisibility(View.GONE);
                holder.setText(R.id.tv_title1, "产线名称");
                holder.setText(R.id.tv_content1, item.getBeltlineName());
                holder.setText(R.id.tv_title2, "品名");
                holder.setText(R.id.tv_content2, item.getProductName());
                holder.setText(R.id.tv_title3, "型号");
                holder.setText(R.id.tv_content3, item.getProductMode());
                holder.setText(R.id.tv_title4, "质量状态");
                holder.setText(R.id.tv_content4, getResources().getStringArray(R.array.qualityStatus)[item.getStatus()]);
                holder.getView(R.id.btn_del).setOnClickListener(v -> BaseNetUtil.actionDialog(InspectionReportActivity.this, NewBaseUrl.workshop_inspectionreport_delete, item.getId() + "", token, "删除" + BaseEnum.INSPECTIONREPORT.name, () -> customer(1, 1, etSearch.getText().toString())));
                holder.getView(R.id.ll_6).setVisibility(View.GONE);

                holder.setText(R.id.tv_time, item.getCreateTime());
                ViewUtil.permissionNew(getApplicationContext(), BaseEnum.PLAN.has(PermEnum.DELETE), holder.getView(R.id.btn_del));
                holder.setText(R.id.tv_title5, "创建人");
                holder.setText(R.id.tv_content5, item.getCreateUser().getRealName());


            }
        };
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_add_scan, menu);
        MenuItem menuItem = menu.findItem(R.id.menu_scan);
        MenuItem menuItem2 = menu.findItem(R.id.menu_add);
        menuItem.setVisible(true);

        if (!PermissonUtils.contains(this, BaseEnum.INSPECTIONREPORT.has(PermEnum.ADD))) {
            menuItem.setVisible(false);
            menuItem2.setVisible(false);
        }

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_add:
//                        Bundle bundle = new Bundle();
//                        bundle.putString("id", getIntent().getStringExtra("id"));
                        IntentUtils.startActivity(InspectionReportActivity.this, InspectionReportAddActivity.class);

                        break;

                    case R.id.menu_scan:
                        if (ViewUtil.checkPer(InspectionReportActivity.this)) {
                            Intent intent = new Intent(InspectionReportActivity.this, CaptureActivity.class);
                            startActivityForResult(intent, SCANNING_CODE);
                        }
                        break;
                }
                return false;
            }
        });
        return true;
    }

    public void customer(Integer page, final Integer type, String search) {
        if (dialog != null) {
            dialog.dismiss();
        }
        GetRequest params = OkHttpUtils
                .get(NewBaseUrl.workshop_inspectionreport_list)
                .params("token", token)
                .params("key", search)
                .params("limit", NewBaseUrl.num).params("page", page.toString());
        for (DialogBean bean : dialogList) {
            params.params(bean.getSubmitName(), bean.getResult());
        }
        params.execute(new StringLoadingCallback(this, mPullToRefreshScrollView,search) {
            @Override
            public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                Log.i("test", BaseEnum.INSPECTIONREPORT.name + "列表: " + result);
                if (type == 1) {
                    list.clear();
                }
                JSONObject jsonObj = JSON.parseObject(result);
                int code = jsonObj.getInteger("code");
                ViewUtil.lagout(code, getApplicationContext());
                if (code == 0) {
                    JSONObject Jpage = jsonObj.getJSONObject("page");
                    initToolBar(BaseEnum.INSPECTIONREPORT.name + "(" + Jpage.getString("totalCount") + ")");
                    List<InspectionReportDto> jsonArray = new ArrayList<InspectionReportDto>(JsonExcludeNull.parseArrayExcludeNull(Jpage.getString("list"), InspectionReportDto.class));
                    list.addAll(jsonArray);

                    if (list.size() == 0) {
                        mMangeNodata.setVisibility(View.VISIBLE);
                    } else {
                        mMangeNodata.setVisibility(View.GONE);
                    }
                    adapter.notifyDataSetChanged();
//                            StaticsCount count = JSON.parseObject(Jpage.getString("staticsCount"), new TypeReference<StaticsCount>() {
//                            });
//                            tvSelect0.setText("待审核(" + count.getCount0() + ")");
//                            tvSelect1.setText("已审核(" + count.getCount1() + ")");

                } else {
                    ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                }

                mPullToRefreshScrollView.onRefreshComplete();
            }
        });
    }

    public void showDialog() {
        if (dialog == null) {
            dialogList.clear();
            dialogList.add(new DialogBean("beltlineId", "产线名称", 1, BaseNetUtil.base(this, NetworkEnum.BELTLINE, mCompanyId)));

            dialogList.add(new DialogBean("productId", "品名", 1, BaseNetUtil.base(this, NetworkEnum.PRODUCT, mCompanyId)));

            dialogList.add(new DialogBean("status", "质量状态", 1, getResources().getStringArray(R.array.qualityStatus)));


            dialog = DialogUtils.selectNewDialog(this, dialogList, new ActionCallback() {
                @Override
                public void run() {
                    customer(1, 1, "");
                    dialog.dismiss();

                }
            });
            dialog.show();
        } else {
            dialog.show();
        }
    }

    @OnClick(R.id.tv_select)
    public void onViewClicked() {
        showDialog();
    }
}
